import {
  getToken,
  removeToken,
  setToken,
  getName,
  setName,
  removeName,
} from "@/utils/auth";
import { login } from "@/api/user.js";
import router from "@/router";
const state = {
  token: getToken(),
  userInfo: {},
  // name: getName(),
};
const mutations = {
  updateToken(state, payload) {
    // 将token注入store库
    state.token = payload;
    // 将token存入本地
    setToken(payload);
  },
  deleteToken(state) {
    state.token = null;
    removeToken();
    removeName();
  },
  // 将用户信息传入store
  setUserInfo(state, payload) {
    state.userInfo = payload;
    console.log(payload.name);
    setName(payload.name);
  },
};
const actions = {
  async login(context, payload) {
    // 发请求获得token
    const res = await login(payload);
    console.log(res);
    context.commit("updateToken", res.data.token.token);
    context.commit("setUserInfo", res.data.user);
  },
  // 登出action
  logout(context) {
    context.commit("deleteToken");
  },
};
export default { namespaced: true, state, mutations, actions };
